package com.xhl.doeverything.service.impl;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import com.xhl.doeverything.dozer.DozerUtils;
import com.xhl.doeverything.entity.StudentRequest;
import com.xhl.doeverything.es.constants.ElasticConstants;
import com.xhl.doeverything.es.index.IndexStudent;
import com.xhl.doeverything.service.StudentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author xionghuilong
 * @description: 学生管理
 * @date 2021/12/3 14:23
 */
@Service
@Slf4j
public class StudentInfoServiceImpl implements StudentInfoService {

    public StudentInfoServiceImpl(){
        log.info("StudentInfoServiceImpl inited!");
    }

    @Resource
    private DozerUtils dozer;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    private String studentIndexName;

    @Override
    public void add(StudentRequest request) {

        IndexStudent student = this.dozer.map(request, IndexStudent.class);

        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index(this.studentIndexName);
        String addStudent = new JSONObject(student, JSONConfig.create()).toString();
        indexRequest.source(addStudent, XContentType.JSON)
                .type(ElasticConstants.DEFAULT_TYPE)
                .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
                .id(String.valueOf(student.getId()));
        try {
            elasticsearchRestTemplate.getClient().index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void edit(StudentRequest request) throws IOException {
        //es
//        String paperIdStr = request;
//        IndexPaper indexPaper = elasticsearchRestTemplate.queryForObject(GetQuery.getById(paperIdStr),IndexPaper.class);
//        indexPaper.setAuditedTopicNum(paperDO.getAuditedTopicNum());
//        indexPaper.setTopicTotal(paperDO.getTopicTotal());
//        indexPaper.setUpdateTime(paperDO.getUpdateTime());
//        UpdateRequest request = new UpdateRequest();
//        String updateStr = new JSONObject(indexPaper, jsonConfig).toString();
//        request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
//        request.doc(updateStr, XContentType.JSON);
//        try {
//            elasticsearchRestTemplate.update(new UpdateQueryBuilder().withIndexName(paperIndexName).withId(paperIdStr).withClass(IndexPaper.class).withUpdateRequest(request).build());
    }
}
